'use client';

import React, {useState, useMemo} from 'react';
import {motion, AnimatePresence} from 'framer-motion';
import {
    PhotoIcon,
    XMarkIcon,
    CheckIcon,
    PlusIcon, // 添加这个导入
} from '@heroicons/react/24/outline';
import {useAppStore} from '@/store';
import type {Activity} from '@/types';
import {cn} from '@/utils';
import Button from '@/components/ui/Button';
import Card, {CardContent} from '@/components/ui/Card';

const AddEntryForm: React.FC = () => {
    const {settings, addActivity, addActivityType} = useAppStore();
    const [selectedActivityType, setSelectedActivityType] = useState('');
    const [customActivityName, setCustomActivityName] = useState('');
    const [showCustomActivityInput, setShowCustomActivityInput] = useState(false);
    const [customActivityCoinValue, setCustomActivityCoinValue] = useState(0);
    const [selectedMood, setSelectedMood] = useState('');
    const [content, setContent] = useState('');
    const [images, setImages] = useState<string[]>([]);
    const [isCustomTime, setIsCustomTime] = useState(false);
    const [customDate, setCustomDate] = useState('');
    const [customTime, setCustomTime] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);

    // 计算预览的金币变化
    const previewCoinChange = useMemo(() => {
        if (!selectedActivityType || !selectedMood) return 0;

        const activityType = settings.activityTypes.find(t => t.name === selectedActivityType);
        const moodConfig = settings.moodConfigs.find(m => m.name === selectedMood);

        const activityCoin = activityType?.coinValue || 0;
        const moodModifier = moodConfig?.coinModifier || 0;

        return activityCoin + moodModifier;
    }, [selectedActivityType, selectedMood, settings]);

    const isFormValid = selectedActivityType && selectedMood;

    const handleSubmit = async () => {
        if (!isFormValid) return;

        setIsSubmitting(true);

        try {
            const activityType = settings.activityTypes.find(t => t.name === selectedActivityType);
            const moodConfig = settings.moodConfigs.find(m => m.name === selectedMood);

            if (!activityType || !moodConfig) return;

            let timestamp = new Date();

            if (isCustomTime && customDate && customTime) {
                timestamp = new Date(`${customDate}T${customTime}`);
            }

            const activity: Omit<Activity, 'id' | 'createdAt' | 'updatedAt'> = {
                title: selectedActivityType,
                activityType: selectedActivityType,
                content: content.trim(),
                mood: selectedMood,
                images,
                timestamp,
                coinChange: previewCoinChange,
            };

            addActivity(activity);

            // 重置表单
            setSelectedActivityType('');
            setSelectedMood('');
            setContent('');
            setImages([]);
            setIsCustomTime(false);
            setCustomDate('');
            setCustomTime('');
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (files) {
            Array.from(files).forEach(file => {
                const reader = new FileReader();
                reader.onload = (e) => {
                    if (e.target?.result && typeof e.target.result === 'string') {
                        setImages(prev => [...prev, e.target.result as string]);
                    }
                };
                reader.readAsDataURL(file);
            });
        }
    };

    const removeImage = (index: number) => {
        setImages(prev => prev.filter((_, i) => i !== index));
    };

    return (
        <div className="max-w-7xl mx-auto p-4">
            {/* 页面标题和操作区域 */}
            <div className="flex items-center justify-between mb-6">
                <div className="text-left flex-1">
                    <h1 className="text-2xl font-bold text-gray-900">记录新事项</h1>
                    <div className="flex items-center gap-4 mt-1">
                        <p className="text-gray-600">记录你的活动和情绪，获得注意力金币</p>

                        {/* 表单状态提示 - 移到标题下方左侧 */}
                        <AnimatePresence>
                            {(!selectedActivityType || !selectedMood) && (
                                <motion.div
                                    initial={{opacity: 0, scale: 0.9, x: -20}}
                                    animate={{opacity: 1, scale: 1, x: 0}}
                                    exit={{opacity: 0, scale: 0.9, x: -20}}
                                    className="flex items-center gap-2 px-3 py-1.5 bg-amber-50 border border-amber-200 rounded-full text-xs text-amber-700"
                                >
                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
                                              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
                                    </svg>
                                    <span>
                                        {!selectedActivityType && '请选择事项'}
                                        {selectedActivityType && !selectedMood && '请选择情绪'}
                                    </span>
                                </motion.div>
                            )}
                        </AnimatePresence>
                    </div>
                </div>

                {/* 右侧操作区域：金币预览和提交按钮 */}
                <div className="flex items-center gap-4">
                    {/* 金币预览 */}
                    <AnimatePresence>
                        {(selectedActivityType && selectedMood) && (
                            <motion.div
                                initial={{opacity: 0, scale: 0.9}}
                                animate={{opacity: 1, scale: 1}}
                                exit={{opacity: 0, scale: 0.9}}
                                className="bg-gradient-to-r from-yellow-50 to-orange-50 border border-yellow-200 rounded-lg px-4 py-2 text-center"
                            >
                                <div className="text-xs text-gray-600">预计金币</div>
                                <div className={cn(
                                    'text-lg font-bold',
                                    previewCoinChange >= 0 ? 'text-green-600' : 'text-red-600'
                                )}>
                                    {previewCoinChange >= 0 ? '+' : ''}{previewCoinChange}
                                </div>
                            </motion.div>
                        )}
                    </AnimatePresence>

                    {/* 提交按钮 */}
                    <Button
                        onClick={handleSubmit}
                        disabled={!isFormValid || isSubmitting}
                        loading={isSubmitting}
                        className="px-6 py-3"
                        size="lg"
                    >
                        <CheckIcon className="w-5 h-5 mr-2"/>
                        {isSubmitting ? '提交中...' : '完成记录'}
                    </Button>
                </div>
            </div>

            {/* 主要表单区域 - 三列布局 */}
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                {/* 选择事项类型 - 第一列 */}
                <Card className="h-fit">
                    <CardContent className="p-4">
                        <h2 className="text-base font-semibold text-gray-900 mb-3 text-center">选择事项</h2>
                        <div className="grid grid-cols-2 gap-2">
                            {settings.activityTypes.map((activityType) => (
                                <motion.button
                                    key={activityType.id}
                                    whileHover={{scale: 1.02}}
                                    whileTap={{scale: 0.98}}
                                    onClick={() => setSelectedActivityType(activityType.name)}
                                    className={cn(
                                        'p-2 rounded-lg border transition-all text-center min-h-[65px] flex flex-col items-center justify-center gap-1',
                                        selectedActivityType === activityType.name
                                            ? 'border-blue-500 bg-blue-50 text-blue-700'
                                            : 'border-gray-200 hover:border-gray-300'
                                    )}
                                >
                                    <span className="text-xl">{activityType.icon}</span>
                                    <span className="text-xs font-medium">{activityType.name}</span>
                                    <span className={cn(
                                        'text-xs',
                                        activityType.coinValue >= 0 ? 'text-green-600' : 'text-red-600'
                                    )}>
                    {activityType.coinValue >= 0 ? '+' : ''}{activityType.coinValue}
                  </span>
                                </motion.button>
                            ))}

                            {/* 添加自定义事项按钮 */}
                            <motion.button
                                whileHover={{scale: 1.02}}
                                whileTap={{scale: 0.98}}
                                onClick={() => setShowCustomActivityInput(true)}
                                className={cn(
                                    'p-2 rounded-lg border transition-all text-center min-h-[65px] flex flex-col items-center justify-center gap-1',
                                    showCustomActivityInput
                                        ? 'border-blue-500 bg-blue-50 text-blue-700'
                                        : 'border-gray-200 hover:border-gray-300 border-dashed'
                                )}
                            >
                                <PlusIcon className="w-5 h-5"/>
                                <span className="text-xs font-medium">自定义</span>
                            </motion.button>
                        </div>

                        {/* 自定义事项输入表单 */}
                        <AnimatePresence>
                            {showCustomActivityInput && (
                                <motion.div
                                    initial={{opacity: 0, height: 0}}
                                    animate={{opacity: 1, height: 'auto'}}
                                    exit={{opacity: 0, height: 0}}
                                    transition={{duration: 0.2}}
                                    className="mt-4 space-y-3"
                                >
                                    <div>
                                        <label className="text-sm font-medium text-gray-700">事项名称</label>
                                        <input
                                            type="text"
                                            value={customActivityName}
                                            onChange={(e) => setCustomActivityName(e.target.value)}
                                            placeholder="输入事项名称"
                                            className="mt-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                        />
                                    </div>

                                    <div>
                                        <label className="text-sm font-medium text-gray-700">金币值</label>
                                        <div className="mt-1 flex items-center gap-2">
                                            <input
                                                type="number"
                                                value={customActivityCoinValue}
                                                onChange={(e) => setCustomActivityCoinValue(Number(e.target.value))}
                                                placeholder="设置金币值"
                                                className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                            />
                                            <span className={cn(
                                                'text-sm font-medium',
                                                customActivityCoinValue >= 0 ? 'text-green-600' : 'text-red-600'
                                            )}>
                        {customActivityCoinValue >= 0 ? '+' : ''}{customActivityCoinValue} 金币
                      </span>
                                        </div>
                                        <p className="mt-1 text-xs text-gray-500">正数表示获得金币，负数表示消耗金币</p>
                                    </div>

                                    <div className="flex items-center gap-2">
                                        <Button
                                            size="sm"
                                            variant="primary"
                                            onClick={async () => {
                                                if (customActivityName.trim()) {
                                                    // 添加新的活动类型
                                                    const newActivityType = {
                                                        name: customActivityName.trim(),
                                                        coinValue: customActivityCoinValue,
                                                        icon: '📝', // 默认图标
                                                        color: '#6B7280', // 默认颜色
                                                        isCustom: true
                                                    };

                                                    addActivityType(newActivityType);
                                                    setSelectedActivityType(customActivityName.trim());
                                                    setShowCustomActivityInput(false);
                                                    setCustomActivityName('');
                                                    setCustomActivityCoinValue(0);
                                                }
                                            }}
                                            disabled={!customActivityName.trim()}
                                        >
                                            <CheckIcon className="w-4 h-4 mr-1"/>
                                            确定
                                        </Button>
                                        <Button
                                            size="sm"
                                            variant="outline"
                                            onClick={() => {
                                                setShowCustomActivityInput(false);
                                                setCustomActivityName('');
                                                setCustomActivityCoinValue(0);
                                            }}
                                        >
                                            取消
                                        </Button>
                                    </div>
                                </motion.div>
                            )}
                        </AnimatePresence>
                    </CardContent>
                </Card>

                {/* 选择情绪 - 第二列 */}
                <Card className="h-fit">
                    <CardContent className="p-4">
                        <h2 className="text-base font-semibold text-gray-900 mb-3 text-center">选择情绪</h2>
                        <div className="grid grid-cols-2 gap-2">
                            {settings.moodConfigs.map((mood) => (
                                <motion.button
                                    key={mood.id}
                                    whileHover={{scale: 1.02}}
                                    whileTap={{scale: 0.98}}
                                    onClick={() => setSelectedMood(mood.name)}
                                    className={cn(
                                        'p-2 rounded-lg border transition-all text-center min-h-[65px] flex flex-col items-center justify-center gap-1',
                                        selectedMood === mood.name
                                            ? 'border-blue-500 bg-blue-50 text-blue-700'
                                            : 'border-gray-200 hover:border-gray-300 text-gray-700'
                                    )}
                                >
                                    <span className="text-lg">{mood.emoji}</span>
                                    <span className="text-xs font-medium leading-tight">{mood.name}</span>
                                    <span className="text-xs text-gray-500">
                    {mood.coinModifier >= 0 ? '+' : ''}{mood.coinModifier}
                  </span>
                                </motion.button>
                            ))}
                        </div>
                    </CardContent>
                </Card>

                {/* 填写详情 - 第三列 */}
                <Card className="h-fit">
                    <CardContent className="p-4 space-y-4">
                        <h2 className="text-base font-semibold text-gray-900 text-center">填写详情</h2>

                        {/* 内容输入 */}
                        <div>
                            <label className="block text-xs font-medium text-gray-700 mb-2">
                                此刻你想说
                            </label>
                            <textarea
                                value={content}
                                onChange={(e) => setContent(e.target.value)}
                                placeholder="关于这件事情的想法..."
                                className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none text-sm"
                                rows={4}
                            />
                        </div>

                        {/* 图片上传 */}
                        <div>
                            <label className="block text-xs font-medium text-gray-700 mb-2">
                                添加图片
                            </label>
                            <div className="border border-dashed border-gray-300 rounded-lg p-3 text-center">
                                <input
                                    type="file"
                                    id="image-upload"
                                    multiple
                                    accept="image/*"
                                    onChange={handleImageUpload}
                                    className="hidden"
                                />
                                <label
                                    htmlFor="image-upload"
                                    className="cursor-pointer flex flex-col items-center"
                                >
                                    <PhotoIcon className="w-6 h-6 text-gray-400 mb-2"/>
                                    <span className="text-xs text-gray-600">点击添加图片</span>
                                </label>
                            </div>

                            {/* 图片预览 */}
                            {images.length > 0 && (
                                <div className="flex flex-wrap gap-2 mt-2">
                                    {images.map((image, index) => (
                                        <div key={index} className="relative">
                                            <img
                                                src={image}
                                                alt={`Upload ${index}`}
                                                className="w-16 h-16 object-cover rounded"
                                            />
                                            <button
                                                onClick={() => removeImage(index)}
                                                className="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white rounded-full flex items-center justify-center"
                                            >
                                                <XMarkIcon className="w-3 h-3"/>
                                            </button>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>

                        {/* 自定义时间 */}
                        <div>
                            <div className="flex items-center gap-2 mb-2">
                                <input
                                    type="checkbox"
                                    id="custom-time"
                                    checked={isCustomTime}
                                    onChange={(e) => setIsCustomTime(e.target.checked)}
                                    className="w-4 h-4 rounded"
                                />
                                <label htmlFor="custom-time" className="text-xs font-medium text-gray-700">
                                    自定义时间
                                </label>
                            </div>

                            <AnimatePresence>
                                {isCustomTime && (
                                    <motion.div
                                        initial={{opacity: 0, height: 0}}
                                        animate={{opacity: 1, height: 'auto'}}
                                        exit={{opacity: 0, height: 0}}
                                        className="grid grid-cols-2 gap-2"
                                    >
                                        <div>
                                            <label className="block text-xs text-gray-600 mb-1">日期</label>
                                            <input
                                                type="date"
                                                value={customDate}
                                                onChange={(e) => setCustomDate(e.target.value)}
                                                className="w-full p-2 border border-gray-300 rounded text-sm"
                                            />
                                        </div>
                                        <div>
                                            <label className="block text-xs text-gray-600 mb-1">时间</label>
                                            <input
                                                type="time"
                                                value={customTime}
                                                onChange={(e) => setCustomTime(e.target.value)}
                                                className="w-full p-2 border border-gray-300 rounded text-sm"
                                            />
                                        </div>
                                    </motion.div>
                                )}
                            </AnimatePresence>
                        </div>
                    </CardContent>
                </Card>
            </div>
        </div>
    );
};

export default AddEntryForm;
